﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using MvcEngine.Mvc.Models.ViewModels;
using MvcEngine.Core;
using MvcEngine.Core.Localization;
using MvcEngine.Core.Utils;
using MvcEngine.Mvc.Extensions;
using MvcEngine.Core.Website;
using MvcEngine.Mvc.Controllers;
using MvcEngine.Core.Content;
using MvcEngine.Mvc.Models;
using AutoMapper;

namespace MvcEngine.Mvc.BackOffice.Controllers
{
    public class SiteController : BaseController
    {
        [AcceptVerbs(HttpVerbs.Get)]
        public MvcEngineModel Edit(Guid siteId)
        {
            var site = SiteManager.Current.GetSite(siteId);
            SiteItemViewModel model = Mapper.Map<Site, SiteItemViewModel>(site);
            model.Pages = ContentManager.Current.GetPages(false);
            model.Skins = SiteManager.Current.GetSkins();
            model.RegistrationTypes = ConvertingUtils.EnumToList<RegistrationType>();
            model.Languages = LocalizationUtil.GetLanguages();
            return model;
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        [ActionName("Edit")]
        public object Save(Guid siteId, Site site)
        {
            if (ModelState.IsValid)
            {
                site.Id = siteId;

                //List<MenuItem> menu = new List<MenuItem>();
                //MenuItem item = new PageMenuItem() { Id = Guid.NewGuid(), PageId = new Guid("702819f2-2959-4a81-9b71-2b3101a1cbee"), ParentId = null, Title = "Home" };
                //MenuItem admin = new MenuItem() { Id = Guid.NewGuid(), Link = "/Development", ParentId = null, Title = "Administration" };
                //MenuItem subItem = new MenuItem() { Id = Guid.NewGuid(), Link = "/Sites", ParentId = admin.Id, Title = "Site configuration" };
                //admin.Items.Add(subItem);
                //site.Fields.Remove("Menu");
                //menu.Add(item);
                //menu.Add(admin);
                //site.Fields.Add(new MvcEngine.Core.Base.EntityField() { Name = "Menu", Value = menu });

                SiteManager.Current.SaveSite(site);
                if (Request.IsAjaxRequest())
                    return Json(new { model = "valid" });
                return Redirect(Url.EditSite(siteId));
            }
            if (Request.IsAjaxRequest())
            {
                return Json(new { model = "invalid", errors = ModelState.GetErrors() });
            }
            return Edit(siteId);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult RefreshCache(Guid siteId)
        {
            CacheManager.Current.ClearCache();
            //if(ControllerContext.HttpContext.Request.IsAjaxRequest())
            return Json(1);
            //else
            //    return Redirect(
        }
    }
}
